<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Http\Requests\UserRequest;
use App\Models\CancelOrderLog;
use App\Models\Feedback;
use App\Models\Order;
use App\Models\ProceedList;
use App\Models\RunErrand;
use App\Models\User;
use App\Services\Facades\OrderService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class UserController extends Controller
{
    // 解密微信用户信息，如头像和昵称
    public function decryptUserInfo(Request $request)
    {
        $user = $request->user();
        $encryptedData = $request->input('encryptedData');
        $iv = $request->input('iv');
        $sessionKey = $request->input('sessionKey');

        $app = Factory::miniProgram([
            'app_id' => env('WECHAT_MINI_APP_APPID'),
            'secret' => env('WECHAT_MINI_APP_SECRET'),
        ]);

        $decryptedData = EasyWeChat::miniProgram()->encryptor->decryptData($sessionKey, $iv, $decryptedData);
        if (isset($decryptedData['errcode'])) {
            return ResponseHelper::error(message: '微信登录失败');
        }
        // 返回解密的用户信息，包括头像和昵称
        return response()->json($decryptedData);
    }

    public function index(Request $request)
    {
        $user = User::with('runErrand')->where('id', $request->user()->id)->first();
        return ResponseHelper::success(data: $user);
    }

    public function update(UserRequest $request)
    {
        $avatar = $request->input('avatar');
        $username = $request->input('username');
        $mobile = $request->input('mobile');
        $request->user()->update(['username' => $username, 'mobile' => $mobile, 'avatar' => $avatar]);
        return ResponseHelper::success();
    }

    /*
     * 收益列表
     * */
    public function proceedList(Request $request)
    {
        $user = $request->user();
        $limit = $request->get('limit', 20);
        $status = $request->get('status', 1);
        $proceedList = ProceedList::with('order')->where('user_id', $user->id)->where('status', $status)->orderBy('id', 'desc')->paginate($limit);

        return ResponseHelper::success(data: [
            'list' => $proceedList->items(),
            'total' => $proceedList->total(),
        ]);
    }

    /**
     * 任务列表-发布者
     *
     * @return JsonResponse
     */
    public function orderList(Request $request): JsonResponse
    {
        $user = $request->user();
        $limit = $request->get('limit', 20);
        $status = $request->get('status');
        if (!in_array($status, [3, 5, 6, 7])) {
            return ResponseHelper::error(message: '暂无数据');
        }
        if ($status == 3) {
            $orderList = Order::with(['user', 'school'])->where('user_id', $user->id)->whereIn('status', [2, 3, 4])->orderBy('id', 'desc')->paginate($limit);
        } else {
            $orderList = Order::with(['user', 'school','runErrand'])->where('user_id', $user->id)->where('status', $status)->orderBy('id', 'desc')->paginate($limit);
        }
        return ResponseHelper::success(data: [
            'list' => $orderList->items(),
            'total' => $orderList->total(),
        ]);
    }

    /*
     * 发布者-取消任务
     * */
    public function cancelOrder(Request $request)
    {
        $user = $request->user();
        $orderId = $request->input('order_id');
        $order = Order::where('id', $orderId)->where('user_id', $user->id)->first();
        if (!$order) {
            return ResponseHelper::error(message: '数据异常');
        }
        if (!in_array($order->status, [2, 3, 4])) {
            return ResponseHelper::error(message: '该任务不能取消');
        }
        try {
            // 开始事务
            DB::beginTransaction();
            $order->status = 7;
            $order->save();
            if ($order->amount >= 0.01) {
                //如果任务有佣金，退回佣金
                $result = OrderService::refund($order->order_number, bcadd($order->amount, $order->handling_fee, 2), bcadd($order->amount, $order->handling_fee, 2), 2);
                Log::info($result->content() ?? null);
            }
            // 提交事务
            DB::commit();
        } catch (\Exception $e) {
            // 发生错误，回滚事务
            DB::rollBack();

            // 处理异常
            return ResponseHelper::error(message: $e->getMessage());
        }
        return ResponseHelper::success(message: '取消成功');
    }

    public
    function loginOut(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return ResponseHelper::success();
    }

    public function feedback(Request $request)
    {
        $user = $request->user();
        $title = $request->input('title');
        $content = $request->input('content');
        $images = $request->input('images');
        if (!$title || !$content) {
            return ResponseHelper::error(message: '请填写反馈内容');
        }
        Feedback::create([
            'title' => $title,
            'content' => $content,
            'images' => $images,
            'user_id' => $user->id
        ]);
        return ResponseHelper::success();
    }

}
